package site.wenneng.dev.objs.bo;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.jetbrains.annotations.NotNull;
import site.wenneng.dev.objs.po.WorkingHoursPO;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Data
@NoArgsConstructor
public class WorkingHoursRemoteBO {

    private List<Header> header;
    private List<List<Item>> items;

    public List<WorkingHoursPO> toPOList() {
        return items.stream().map(item -> {
            WorkingHoursPO po = new WorkingHoursPO();
            po.setTaskId(getValueByName(item, "任务编号").orElse(""));
            po.setWorkingDate(getTextByName(item, "工时填报日期").map(LocalDate::parse).orElse(null));
            po.setWorkingHours(getValueByName(item, "投入工时").map(BigDecimal::new).orElse(BigDecimal.ZERO));
            po.setProgress(getValueByName(item, "进度").map(BigDecimal::new).orElse(BigDecimal.ZERO));
            return po;
        }).collect(Collectors.toList());
    }

    @NotNull
    private String getDIdByName(String name) {
        return header.stream()
                .filter(item -> item.text.equals(name))
                .map(Header::getDId)
                .findFirst()
                .orElse("");
    }

    private Optional<String> getValueByName(List<Item> items, String name) {
        return items.stream()
                .filter(item -> Objects.equals(getDIdByName(name), item.dId))
                .map(Item::getValue)
                .findFirst();
    }

    @SuppressWarnings("SameParameterValue")
    private Optional<String> getTextByName(List<Item> items, String name) {
        return items.stream()
                .filter(item -> Objects.equals(getDIdByName(name), item.dId))
                .map(Item::getText)
                .findFirst();
    }

    @Data
    public static class Header {
        @JsonProperty("dId")
        private String dId;
        private String text;
    }

    @Data
    public static class Item {
        @JsonProperty("dId")
        private String dId;
        private String value;
        private String text;
    }


}
